import * as moment from 'moment';
import {
  Body,
  Controller,
  Get,
  Header,
  HttpCode,
  Param,
  Post,
  Res,
  HttpStatus,
} from '@nestjs/common';
import type { Response } from 'express';
import { ProductService } from './product.service';
import { ProductAddDTO } from './product.dto';
import { ValidationPipe } from './pipe';

@Controller('product')
export class ProductController {
  constructor(private readonly productService: ProductService) {}

  @Get()
  @Header('Cache-Control', 'no-cache')
  public getProducts() {
    return this.productService.getProducts();
  }

  @Get(':id')
  @Header('Cache-Control', 'no-cache')
  public getProduct(
    @Param('id')
    productId: string,
  ) {
    return this.productService.getProduct(productId);
  }

  @Post('add')
  @HttpCode(HttpStatus.OK)
  @Header('Content-Type', 'application/vnd.openxmlformats')
  public async insertProduct(
    @Body(new ValidationPipe()) data: ProductAddDTO,
    @Res() response: Response,
  ) {
    const { sn, data: product } = await this.productService.insertProducts(
      data.product,
    );

    console.time('导出EXCEL');
    const file = await this.productService.exportExcel({
      sn,
      product,
      groupSize: data.groupSize,
      sheetGroup: data.sheetGroup,
    });
    console.timeEnd('导出EXCEL');

    const fileName = encodeURIComponent(
      moment().format('YYYY-MM-DD') + `计划-批次号${sn}.xlsx`,
    );

    response.setHeader(
      'Content-Disposition',
      'attachment; filename=' + fileName,
    );
    console.log('fileName', decodeURIComponent(fileName));

    response.end(file);
  }
}
